export default class TalkObject {
    static instance = null;
    constructor() {
        if (!TalkObject.instance) {
            TalkObject.instance = this;
            this.talkList = [];                     //会话列表 
            this.messageList = [];                  //临时存放消息的数组
            this.member_id = 0;
            this.port = '';
            this.sertype = '';
            this.nowTalkId = 0;                     //正在聊天的talk_id
            this.fristClientMsgId = '';
            this.p = 1;
            this.on = {
                /* 新信息提醒回调*/
                onNewChatAlert: (msg) => {
                    console.log("alert!", msg)
                },
                /* 新消息聊天页回调 */
                onTalkWithMsg() {
                },
                /* 列表刷新回调*/
                onListRefresh: (list) => {
                    console.log(list)
                },
                /* 会话详情刷新回调*/
                onTalkDetailRefresh: (msg) => {
                    console.log(msg);
                }
            }
        }
        return TalkObject.instance;
    }
    /* 获取会话列表（用于会话列表页）*/
    getTalkList() {
        //1.删除 _child
        let list = this.talkList.map(item => {
            const obj = {};
            for (let i in item) { if (i != '_child') { obj[i] = item[i] } }
            obj.lastMessage = item._child[item._child.length - 1];
            obj.msgLength = item._child.length;
            obj.dataTime = obj.lastMessage ? obj.lastMessage.head.dateTime : '';
            return obj;
        })
        // 2.倒序
        return { code: 200, data: list };
    }
    /*获取会话的会话详情（用于会话详情页）*/
    getTalkDetail(talk_id) {
        const item = this.talkList.find(item => {
            if (item.id == talk_id) {
                return item;
            }
        });
        if (!item) {
            return {
                code: 301,
                data: "会话不存在！"
            };
        }
        const personMap = new Map();
        item.talkPartakeMembers.forEach(item => {
            personMap.set(item.member_id, item);
        });
        let list = item._child.map(item => {
            var content = {},
                person = personMap.get(item.head.fromMemberId + '');
            content = Object.assign(content, person, item.body);
            return content;
        })
        item.notReadNum = 0;
        console.log('notReadNum清空！')
        // list = list.reverse();
        return {
            code: 200,
            data: list
        };
    }
    getTalkDetail01(talk_id) {
        const item = this.talkList.find(item => {
            if (item.id == talk_id) {
                return item;
            }
        });
        if (!item) {
            return { code: 301, data: "会话不存在！" };
        }
        var list = item.talkPartakeMembers.filter(item => {
            if (item.member_id != this.member_id) {
                return item;
            }
        });
        return { code: 200, data: list }
    }
    /*获取会话的聊天记录（用于会话聊天页）*/
    getChat(talk_id) {
        if (!talk_id) { return { code: 301, data: "参数talk_id缺失！" } }
        // 1.在会话列表中找到会话对象
        let item = this.talkList.find(item => { if (item.id == talk_id) { return item } })
        if (!item) { return { code: 301, data: "会话不存在!" } }
        // 2.定义每页显示消息数量
        const length = 10;
        // 3.未读消息清空
        item.notReadNum = 0;
        // 4.消息数组 ，初始化数组开始截取下标，和结束下标
        let msgArray = item._child;
        let start = msgArray.length - 1,                //从第几条消息开始获取历史记录
            end;                                        //结束下标
        // 5.正在聊天的用户发生改变时，重置 nowTalkId，p
        // 6.根据fristClientMsgId 找到 开始下标
        if (this.nowTalkId == talk_id) {
            let index;
            for (let i = item._child.length - 1; i >= 0; i--) {
                let target = item._child[i];
                if (target.head.clientMsgId == this.fristClientMsgId) {
                    index = i;
                    break;
                }
            }
            start = index - (this.p) * length;
            this.p++;
        } else {
            this.fristClientMsgId = msgArray[msgArray.length - 1].head.clientMsgId;
            this.nowTalkId = talk_id;
            this.p = 1;
        }
        // 6.得到 end 下标
        end = start - length;
        // 7.得到的历史记录
        const list = msgArray.slice(end < 0 ? 0 : end, start + 1);
        // 8.获取用户信息，改变消息格式
        const personMap = new Map();
        item.talkPartakeMembers.forEach(item => {
            personMap.set(item.member_id, item);
        });
        const res = list.map(item => {
            let msg = {};
            if (item.head.fromMemberId == this.member_id) {
                msg.isMe = true;
            } else {
                msg.isMe = false;
            }
            const person = personMap.get(item.head.fromMemberId + '');
            msg = Object.assign(msg, person, item.body);
            msg.clientMsgId = item.head.clientMsgId;
            msg.dateTime = item.head.dateTime;
            return msg;
        })
        // 9.本地存储更新
        this.initLocalStorage();
        // 10.未读消息清空，本地列表更新
        this.on.onListRefresh();
        return { code: 200, data: res };
    }
    /*会话置顶*/
    topTalk(talk_id) {
        const item = this.talkList.find((data, index) => {
            if (data.id == talk_id) {
                var target = this.talkList.splice(index, 1)[0];
                target.stick = true;
                target.oldIndex = index;
                this.talkList.unshift(target);
                return data;
            }
        })
        if (item) {
            return { code: 200, data: "置顶消息成功！" }
        }
        return { code: 301, data: "未找到会话！" }
    }
    /*添加单个会话（用于创建临时会话）*/
    addTalk(talk) {
        //1.判断传入的talk的字段是否存在
        console.log("创建会话！")
        if (!talk) {
            return { code: 301, data: "参数会话为空！" }
        }
        //2.判断talk.id是否存在于talkList的元素中，如果存在return
        const item = this.talkList.find(item => {
            if (item.id == talk.id) {
                return item;
            }
        })
        if (!item) {
            //3.将talk放存talkList的最后面,初始化未读消息数量
            talk._child ? '' : talk._child = [];
            talk.notReadNum = 0;
            console.log('notReadNum清空！')
            this.talkList.push(talk);
        }
        //从消息队列中取出消息、并删除消息
        for (let i = 0; i < this.messageList.length; i++) {
            console.log(this.messageList[i])
            if (this.messageList[i].body.talk_id == talk.id) {
                talk._child.push(this.messageList[i]);
                this.messageList.splice(i, 1);
                i--;
            }
        }
        //4.调用this.on.onListRefresh
        this.on.onListRefresh(this.talkList);
        //5.本地聊天记录设置
        this.initLocalStorage();
    }
    /*(talk类型)添加单个会话的聊天记录（用于会话发送消息和接收消息）*/
    addChat(talk_id, msg, callback) {
        //1.判断传入的msg的字段是否存在
        if (!msg) { return { code: 301, data: '参数msg为空！' } }
        //2.判断msg.head.action是否等于‘talk’
        if (msg.head.action != "talk") { return { code: 301, data: "添加单个会话 消息类型错误！" } }
        const item = this.talkList.find(item => { if (item.id == talk_id) { return item; } })
        if (!item) {
            this.messageList.push(msg);
            callback && callback();
            return { code: 200, data: "会话不存在，需要获取临时会话列表！" }
        }
        for (let i = item._child.length - 1; i >= 0; i--) {
            const message = item._child[i];
            if (message.head.clientMsgId == msg.head.clientMsgId) {
                return { code: 301, data: "该消息已存在。" }
            }
        }
        if (this.nowTalkId == msg.body.talk_id) {
            const personMap = new Map();
            item.talkPartakeMembers.forEach(item => {
                personMap.set(item.member_id, item);
            });
            let ProcessMsg = {};
            if (msg.head.fromMemberId == this.member_id) {
                ProcessMsg.isMe = true;
            } else {
                ProcessMsg.isMe = false;
            }
            const person = personMap.get(msg.head.fromMemberId + '');
            ProcessMsg = Object.assign(ProcessMsg, person, msg.body);
            ProcessMsg.clientMsgId = msg.head.clientMsgId;
            this.on.onTalkWithMsg(ProcessMsg);
        } else {
            if (msg.head.fromMemberId != this.member_id) {
                item.notReadNum++;
                this.on.onNewChatAlert(msg);
            }
        }
        //4.判断msg.head.sendMemberId是否存在于talk.talkPartakeMemberIds中
        if (item.talkPartakeMemberIds.includes(msg.head.fromMemberId)) {
            // return { code: 301, data: "错误！" }
        }
        item._child.push(msg);
        //5.on 调用...
        this.on.onListRefresh();
        this.initLocalStorage();          //更新本地存储
    }
    /*用户登录后初始化操作*/
    setMemberId(data) {
        this.member_id = data.member_id;
        this.sertype = data.sertype;
        this.port = data.port;
        const talkList = localStorage.getItem(`${this.member_id}~${this.sertype}~${this.port}`);
        if (talkList) {
            this.talkList = JSON.parse(talkList);
        }
    }
    /*改变消息状态*/
    changeMessageStatus(clientMsgId) {
        for (let i = 0; i < this.talkList.length; i++) {
            for (let j = 0; j < this.talkList[i]._child.length; j++) {
                var data = this.talkList[i]._child[j];
                if (data.head.clientMsgId == clientMsgId) {
                    data.client.sendStatus = 3;
                    data.client.sendTime = Date.now();
                    return
                }
            }
        }
    }
    /*通知用户发送消息失败*/
    sendMessageFail(msg) {
        console.log("发送消息失败！", msg);
    }
    /*添加回调函数*/
    addCallBack(newChatAlert, listRefresh, talkDetailRefresh, TalkWithMsg) {
        this.on.onNewChatAlert = newChatAlert ? newChatAlert : this.on.onNewChatAlert;
        this.on.onListRefresh = listRefresh ? listRefresh : this.on.onListRefresh;
        this.on.onTalkDetailRefresh = talkDetailRefresh ? talkDetailRefresh : this.on.onTalkDetailRefresh;
        this.on.onTalkWithMsg = TalkWithMsg ? TalkWithMsg : this.on.onTalkWithMsg;
    }
    /*存储loginData*/
    initSessionStorage(loginData) {
        var data = JSON.stringify(loginData);
        sessionStorage.setItem('config', data)
    }
    /*存储用户聊天记录*/
    initLocalStorage() {
        localStorage.setItem(`${this.member_id}~${this.sertype}~${this.port}`, JSON.stringify(this.talkList));
    }
    /*取出用户聊天记录*/
    fetchLocalStorage(member_id, sertype, port) {
        var data = localStorage.getItem(`${member_id}~${sertype}~${port}`);
        data = JSON.parse(data);
        if (data) { return { code: 200, data: data } } else { return { code: 301, data: '记录不存在' } }
    }
    /*初始化聊天记录*/
    initTalkList(data) {
        this.talkList = data;
    }
    /*用户退出会话*/
    exit() {
        this.p = 1;
        this.nowTalkId = 0;
        this.fristClientMsgId = 0;
    }
}
// function test() {
//     var now = new Date();
//     var str,
//         second = now.getSeconds(),
//         minSecond = (Date.now() + '').slice(-3);
//     str = second + '.' + minSecond;
//     return str;
// }